<!--
- Author:   .
- Date:    2017/3/4.
- File:    index.vue.
-->
<template>
  <div>
    <app-down></app-down>
    <div class="Web_Box">
      <div style="position: fixed; z-index: 2;width: 100%">
        <!--<i class="TransparentBut TransparentReturn iconfont icon-leftdot" @click="back"></i>-->
        <router-link :to="{name: 'cart-list'}">
          <i class="TransparentBut TransparentList iconfont icon-shoppingcart"></i>
        </router-link>
        <!--<i class="TransparentBut TransparentCollection iconfont icon-collection" :class="{'collected': goodsCommonInfo.fav_state == 1}" @click="switchCollect"></i>-->
      </div>

      <div class="CommodityDetails hidden">
        <mt-swipe :auto="0" class="swiper-container bg_fff" style="height: 16rem">
          <mt-swipe-item class="swiper-slide" v-for="(item,index) in goodsCommonInfo.showimage" :key="index">
            <div class="swiper-slide">
              <img class="swipe-img" style="width: 100%" :src="$config.website + $config.goodsImgSrc + item" alt=""/>
            </div>
          </mt-swipe-item>
        </mt-swipe>
        <!--活动-->
        <div class="active_box" v-if="goodsCommonInfo.groupbuy_info">
          <div class="active_cont f-cb">
            <div class="text">
              <p class="slh w5rem">{{goodsCommonInfo.groupbuy_info.groupbuy_name}}</p>
              <p class="f12" v-if="goodsCommonInfo.groupbuy_info.upper_limit > 0">仅限购{{goodsCommonInfo.groupbuy_info.upper_limit}}件</p>
            </div>
            <div class="disib vm daojishi fr " v-if="goodsCommonInfo.groupbuy_info.type == 1">
              <p class="f12 pb5">距结束仅剩</p>
              <span class="timem disib vm">{{timeRemain.days}}</span><span class=" disib vm">&nbsp;天&nbsp;</span><span class="timem disib vm">{{timeRemain.hours}}</span><span class=" disib vm">&nbsp;时&nbsp;</span><span class="timem disib vm">{{timeRemain.minutes}}</span><span class="disib vm">&nbsp;分&nbsp;</span><span class="timem disib vm">{{timeRemain.seconds}}</span><span class="disib vm">&nbsp;秒&nbsp;</span>
            </div>
          </div>
        </div>
        <!--活动 end-->
        <!--商品基础信息Start-->
        <div class="BasicInfo">
          <div class="pl20 pr20 hidden">
            <p class="Price" v-show="orderType != '4'">
              <span class="PresentPrice">￥{{goodsCommonInfo.goods_marketprice | toFixed(0)}}</span><span class="OriginalPrice">￥{{goodsCommonInfo.goods_price | discount(goodsCommonInfo.groupbuy_rebate)}}</span><span style="color: #f5d607" v-show="memberInfo.is_firstbuy == 0">{{goodsCommonInfo.discount * 10 | toFixed(1)}}折</span><span style="color: #f5d607" v-show="memberInfo.is_firstbuy != 0">7.35折</span>
            </p>
            <p class="Price" v-show="orderType == '4'">
              <span class="PresentPrice">{{goodsCommonInfo.goods_price | discount(goodsCommonInfo.groupbuy_rebate)}}红积分</span>
            </p>
            <h1 class="slh2">{{goodsCommonInfo.goods_name}}
            </h1>
            <div class="detail_text f24">{{goodsCommonInfo.goods_jingle}}</div>
          </div>
        </div>
        <!--商品基础信息End-->
        <!--<p class="Freight mb10"><span class="cr_595757">运费：中国大陆地区包邮；港澳台，及境外请联系客服</span></p>-->
        <p class="Freight mb10" v-show="orderType == '4'"><span class="cr_595757" style="font-size: 14px;">红积分商品为快递发货，需要另外支付运费</span></p>
        <!--视频Start-->
        <div class="video_block bg_fff" v-show="goodsCommonInfo.youku_url" style="margin: 0 auto; text-align: center; padding: 0.5rem" v-html="resetIframWH($utils.HTMLDecode(goodsCommonInfo.youku_url))">

        </div>
        <!--视频End-->
        <!--商品评价Start-->
        <div class="CommodityEvaluation mt20 bor_b_dcdddd" v-show="false">
          <div class="tit">
            <h2>商品评价 ({{goodsCommentCount}})</h2>
            <div class="data disn">好评率<span class="cr_ff5c36">100%</span></div>
          </div>
          <div class="CommentList" v-show="goodsComment.data.length > 0">
            <ul>
              <li v-for="item in goodsComment.data" v-show="item.geval_state == 0 || item.geval_frommemberid == memberInfo.member_id">
                <div class="user">
                  <div class="pic"><img :src="$config.website + $config.avatarSrc + item.member_avatar" alt=""/></div>
                  <span>{{item.member_name}}</span></div>
                <p class="text">{{item.geval_content}}</p>
                <p class="date">{{item.geval_addtime}}</p>
              </li>
            </ul>
            <div class="more" @click="gotoCommentList">查看更多评价</div>
            <!--<div v-show="goodsComment.allLoaded" style="text-align: center;padding: 0.5rem">没有更多评价了~</div>-->
          </div>
        </div>
        <!--商品评价End-->
        <!--上拉Start-->
        <div class="DetailsEntry">商品详情</div>
        <!--上拉End-->
        <!--商品详情Start-->
        <div>
          <div id="xiangqing" v-html="goodsCommonInfo.bodys" v-show="goodsCommonInfo.bodys!=''">

          </div>
          <div style="padding: 0.5rem 0;text-align: center" v-show="goodsCommonInfo.bodys==''">
            暂时没有详情介绍
          </div>
        </div>
        <!--商品详情End-->

      </div>
    </div>
    <div ref="goods-detail-bottom" class="PurchaseOperation gd" style="height: auto;margin-top: -50px">
      <!--<div class="left fl">
        <ul>
          <li><i class="iconfont icon-customerservice"></i> <span>客服</span></li>
          <li><i class="iconfont icon-shop"></i> <span>店铺</span></li>
          <li><i class="iconfont icon-classification"></i> <span>分类</span></li>
        </ul>
      </div>-->
      <div class="left fl">
        <ul>
          <li @click="gotoHome"><i class="iconfont icon-home"></i> <span>首页</span></li>
          <li @click="gotoCart"><i class="iconfont icon-shoppingcart"></i> <span>购物车</span></li>
        </ul>
      </div>
      <button type="button" class="but bg_c3d600" @click="buyClick(0)">加入购物车</button>
      <button type="button" class="but bg_45a73a" @click="buyClick(1)">立即购买</button>
    </div>
    <!--弹窗-->
    <div v-if="addToCartModelShow">
      <div class="PopBg" @click="switchAddToCartModelShow(false)"></div>
      <!--选择商品属性弹窗Start-->
      <div class="AttributeSelectionPop " id="AttributeSelectionPop">
        <div class="BasicInfo"><i class="iconfont icon-close" @click="switchAddToCartModelShow(false)"></i>
          <div class="pic" style="border: none">
            <img :src="$config.website + $config.goodsImgSrc + goodsInfo.goods_image" alt=""/></div>
          <p class="Price fl" v-show="memberInfo.is_firstbuy == 0 && goodsCommonInfo.discount != 0">￥{{goodsInfo.goods_price * goodsCommonInfo.discount | toFixed(0)}}</p>
          <!--<p class="Price fl" v-show="memberInfo.is_firstbuy == 0 && goodsCommonInfo.discount == 0">￥{{goodsInfo.goods_price }}</p>-->
          <p class="Price fl" v-show="memberInfo.is_firstbuy != 0">￥{{goodsInfo.goods_price * goodsCommonInfo.discount | toFixed(0)}}</p>
          <p class="Price fl" v-show="orderType == '4'">{{goodsInfo.goods_price | discount(goodsCommonInfo.groupbuy_rebate)}}红积分</p>
          <p class="Stock c">库存<span class="ml20">{{goodsInfo.goods_storage}}</span></p>
        </div>
        <div style="max-height:12rem;overflow:auto;">
          <div class="AttributeList" v-for="(attributeClassify, classifyIndex) in goodsAttribute.attri_list">
            <h3>{{attributeClassify.name}}</h3>
            <ul>
              <li v-for="attribute in attributeClassify.list" :class="{'on': selectedAttributeIdList[classifyIndex] == attribute.id}" @click="selectAttributeClick(attribute.id, classifyIndex)">{{attribute.name}}
              </li>
            </ul>
          </div>
        </div>
        <div class="Number" v-show="memberInfo.is_firstbuy == '0'">
          <h3 v-show="goodsCommonInfo.goods_kind != '2'">数量
            <span class="Purchase"></span><span class="Purchase" v-if="goodsCommonInfo.groupbuy_info && goodsCommonInfo.groupbuy_info.upper_limit > 0">(限购{{goodsCommonInfo.groupbuy_info.upper_limit}}件)</span>
          </h3>
          <div class="QuantityControl" v-show="goodsCommonInfo.goods_kind != '2'">
            <i class="iconfont icon-jian1" :class="{'no': parseInt(buyNum) <= 1}" @click="reduceNum"></i>
            <input type="tel" v-model="buyNum" @blur="handleNumChange">
            <i class="iconfont icon-jia1" :class="{'no': parseInt(buyNum) >= this.goodsInfo.goods_storage || (goodsCommonInfo.groupbuy_info && buyNum >= parseInt(goodsCommonInfo.groupbuy_info.upper_limit))}" @click="addNum"></i>
          </div>
        </div>
        <div class="OperationButton f-cb">
          <button type="button" :class="{'bg_45a73a': goodsInfo.goods_storage > 0, 'bg_d3d2d2': goodsInfo.goods_storage <= 0}" style="width: 100%" @click="buyConfirm">确定</button>
        </div>
      </div>
    </div>
    <!--选择商品属性弹窗End-->
    <footer-tab></footer-tab>
  </div>
</template>

<script>
  import {Swipe, SwipeItem} from 'mint-ui'
  import {mapModules, mapRules} from 'vuet'

  export default {
    beforeRouteEnter(to, from, next) {
      next(vm => {
        vm.from = from.name
        vm.toFullPath = to.fullPath
      })
    },
    mixins: [
      mapModules({memberInfo: 'memberInfo'}),
      mapRules({need: 'memberInfo'})
    ],
    data() {
      return {
        orderType: this.$route.query.orderType || '1', // 1：普通商品， 4：红积分商品
        from: null,
        toFullPath: null,
        goodsCommonid: '189',
        goodId: this.$route.params.id,
        goodsCommonInfo: {}, // 商品通用信息
        goodsInfo: {}, // 具体规格的商品信息
        goodsAttribute: {}, // 商品规格
        goodsComment: {requested: false, loading: false, allLoaded: false, page: 1, pageSize: 10, data: []},
        goodsCommentCount: 0,
        addToCartModelShow: false,
        selectedAttributeIdList: [],
        buyNum: 1,
        buyActionType: 0, // 购买操作类型：0加入购物车，1直接购买
        timeRemain: {days: 0, hours: 0, minutes: 0, seconds: 0},
        countdownInterval: null
      }
    },
    components: {
      'mtSwipe': Swipe,
      'mtSwipeItem': SwipeItem
    },
    created() {
      setTimeout(() => {
        this.getGoodsCommonInfo()
        this.getGoodsComment(1, 1)
        this.getGoodsAttributeList()
      }, 700)
      if (this.$utils.isIphoneX()) {
        this.$refs['goods-detail-bottom'].style.paddingBottom = '34px'
      }
    },
    beforeDestroy() {
      clearInterval(this.countdownInterval)
    },
    watch: {
      // 如果路由有变化，会再次执行该方法
      $route() {
        this.init()
      }
    },
    computed: {
      // 购买基数
      packNum: function () {
        return parseInt(this.goodsCommonInfo.goods_add_num || 1)
      }
    },
    methods: {
      h5PayCallback() {
      },
      gotoCart() {
        this.$router.push({name: 'cart-list'})
      },
      gotoHome() {
        this.$router.push({name: 'home'})
//        window.location.href = 'http://' + window.location.host + '/wap/' // ios微信分享要如此跳转后才能正确分享
      },
      back() {
        console.log(this.from)
        if (this.from) {
          this.$router.go(-1)
        } else {
          this.$router.push({name: 'home'})
        }
      },
      init() {
        this.initData()
        this.getGoodsCommonInfo()
        this.getGoodsComment(1, 1)
      },
      initData() {
        this.goodsCommonid = this.goodsCommonid
        this.goodsId = ''
        this.goodsCommonInfo = {}
        this.goodsAttribute = {} // 商品规格
        this.goodsComment = {requested: false, loading: false, allLoaded: false, page: 1, pageSize: 10, data: []}
        this.addToCartModelShow = false
        this.selectedAttributeIdList = []
        this.buyNum = 1
        this.buyActionType = 0 // 购买操作类型：0加入购物车，1直接购买
        this.timeRemain = {days: 0, hours: 0, minutes: 0, seconds: 0}
        this.countdownInterval = null
      },
      switchArriveModelShow(boolValue) {
        this.arriveNoticeModelShow = boolValue
      },
      handleNumChange() {
        console.log('blur..')
        if (this.buyNum == '' || this.buyNum == 0) {
          this.buyNum = 1
          return
        }
        if (parseInt(this.buyNum) > parseInt(this.goodsInfo.goods_storage)) {
          this.buyNum = parseInt(this.goodsInfo.goods_storage)
        }
      },
      getGoodsCommonInfo() {
        this.$request.getGoodsCommonInfo(this.goodsCommonid, this.memberInfo.member_id).then(data => {
          this.goodsCommonInfo = data
          this.getGoodsAttributeList(this.goodsCommonid)
          if (data.groupbuy_info) {
            this.getTimeRemain(data.groupbuy_info.end_time)
            clearInterval(this.countdownInterval)
            this.countdownInterval = setInterval(() => {
              this.getTimeRemain(data.groupbuy_info.end_time)
            }, 1000)
          }
        }).catch(e => {
          this.$toast('获取商品详情失败:' + e.msg)
        })
      },
      getGoodsComment(page, pageSize) {
        this.goodsComment.loading = true
        this.$request.getGoodsCommentList(this.goodsCommonid, page, pageSize).then(data => {
          if (this.$utils.isEmptyObject(data)) {
            return
          }
          if (data.data.length < this.goodsComment.pageSize) {
            this.goodsComment.allLoaded = true
          }
          this.goodsCommentCount = data.count
          this.goodsComment.data = [...this.goodsComment, ...data.data]
        }).finally(() => {
          this.goodsComment.requested = true
          this.goodsComment.loading = false
        })
      },
      getGoodsAttributeList() {
        this.$request.getGoodsAttributeList(this.goodsCommonid).then(data => { // 不传规格数组，返回商品规格列表
          this.goodsAttribute = data
          for (let i = 0; i < data.goods_info.goods_spec.length; i++) {
            this.selectedAttributeIdList[i] = data.goods_info.goods_spec[i].id
          }
          this.goodsInfo = data.goods_info
        })
      },
      async selectAttributeClick(id, index) {
        this.$set(this.selectedAttributeIdList, index, id)
        try {
          let data = await this.$request.getGoodsAttributeList(this.goodsCommonid, this.selectedAttributeIdList) // 传规格数组，返回具体商品
          console.log('222', data)
          this.goodsInfo = data.goods_info
        } catch (e) {
          this.$toast('选择规格失败:' + e.msg)
        }
      },
      gotoCommentList() {
        this.$router.push({
          name: 'comment-list',
          params: {id: this.goodsCommonid},
          query: {commonid: this.goodsCommonid}
        })
      },
      switchCollect() {
        if (this.goodsCommonInfo.fav_state == 0) { // 未收藏过
          this.addCollect()
        } else {
          this.delCollect()
        }
      },
      addCollect() {
        this.$request.addCollect(this.goodsCommonInfo.goods_commonid).then(data => {
          this.$toast('添加收藏成功')
          this.goodsCommonInfo.fav_state = 1
        }).catch(e => {
          this.$toast('添加收藏失败:' + e.msg)
        })
      },
      delCollect() {
        this.$request.delCollect(this.goodsCommonInfo.goods_commonid).then(data => {
          this.$toast('取消收藏成功')
          this.goodsCommonInfo.fav_state = 0
        }).catch(e => {
          this.$toast('取消收藏失败:' + e.msg)
        })
      },
      addNum() {
        if (parseInt(this.buyNum) >= parseInt(this.goodsInfo.goods_storage)) {
          this.$toast('超过商品库存数量了~')
          return
        }
        if (this.goodsCommonInfo.groupbuy_info && parseInt(this.buyNum) >= parseInt(this.goodsCommonInfo.groupbuy_info.upper_limit)) {
          this.$toast('超过限购数量了~')
          return
        }
        this.buyNum++
      },
      reduceNum() {
        if (parseInt(this.buyNum) <= 1) {
          return
        }
        this.buyNum--
      },
      selectGoodsAttr() {
        return new Promise((resolve, reject) => {
          for (let i = 0; i < this.goodsAttribute.attri_list.length; i++) {
            if (!this.selectedAttributeIdList[i]) {
              reject({msg: '请选择 ' + this.goodsAttribute.attri_list[i].name})
            }
          }
          this.$request.getGoodsAttributeList(this.goodsCommonid, this.selectedAttributeIdList).then(goodsCommonInfo => {
            if (!goodsCommonInfo.goods_info.goods_id) {
              reject({msg: '该规格商品不存在'})
            }
            if (!goodsCommonInfo.goods_info.goods_serial) {
              reject({msg: '未能查询到该商品的库存'})
            }
            this.goodsId = goodsCommonInfo.goods_info.goods_id
            this.$request.getErpStorage(goodsCommonInfo.goods_info.goods_serial).then(storage => {
              this.storage = parseInt(storage)
              resolve({goodsCommonInfo: goodsCommonInfo, storage: storage})
            }).catch(e => {
              reject({msg: '查询该规格商品的库存失败'})
            })
          }).catch(e => {
            reject({msg: '获取该规格商品失败'})
          })
        })
      },
      buyClick(buyActionType) {
        this.buyActionType = buyActionType
        this.addToCartModelShow = true
      },
      getGoodsInfoByAttr() {
        return new Promise((resolve, reject) => {
          for (let i = 0; i < this.goodsAttribute.attri_list.length; i++) {
            if (!this.selectedAttributeIdList[i]) {
              reject({msg: '请选择 ' + this.goodsAttribute.attri_list[i].name})
            }
          }
          this.$request.getGoodsAttributeList(this.goodsCommonInfo.goods_commonid, this.selectedAttributeIdList).then(data => {
            if (!data.goods_info.goods_id) {
              reject({msg: '该规格商品不存在'})
            }
            resolve(data.goods_info)
          }).catch(e => {
            reject({msg: '获取该规格商品失败'})
          })
        })
      },
      async buyConfirm() {
        try {
          let goodsInfo = await this.getGoodsInfoByAttr()
          let cartId = await this.$request.addGoodsToCart(goodsInfo.goods_id, this.buyNum)
          if (parseInt(goodsInfo.goods_storage) < parseInt(this.buyNum)) {
            this.$toast('当前库存不足, 请注意购买数量')
            return
          }
          if (this.buyActionType === 0) { // 只是加入购物车
            this.switchAddToCartModelShow(false)
            this.$toast('加入购物车成功')
          } else if (this.buyActionType === 1) { // 立即购买：加入购物车-> 订单确认页
            this.switchAddToCartModelShow(false)
            this.$router.push({name: 'order-confirm', query: {cart: cartId, orderType: this.orderType}})
            // if (this.orderType == '2') {
            //   this.$router.push({name: 'hong-order-confirm', query: {cart: cartId, orderType: '2'}})
            // } else {
            //   this.$router.push({name: 'order-confirm', query: {cart: cartId, orderType: '1'}})
            // }
          }
        } catch (e) {
          console.error('加入购物车失败', e)
          this.$toast('加入购物车失败:' + e.msg)
          if (e.msg == '请先注册') {
            this.$router.push({name: 'login-message'})
          }
        }
      },
      cancleNewGoods() {
        this.switchNewGoodsNoticeModelShow(false)
        this.switchAddToCartModelShow(true)
      },
      switchAddToCartModelShow(boolValue) {
        this.addToCartModelShow = boolValue
      },
      switchNewGoodsNoticeModelShow(boolValue) {
        this.newGoodsNoticeModelShow = boolValue
      },
      gotoGoodsDetail(goodsCommonid) {
        this.$router.push({name: 'goods-detail', params: {id: goodsCommonid}})
      },
      // 去除iframe字符串的宽高
      resetIframWH(html) {
        html = html.replace(/height=\d+/g, '')
        html = html.replace(/width=\d+/g, 'width="100%"')
        return html
      },
      getTimeRemain(endTimeTamp) {
        if (endTimeTamp) {
          let currentTime = new Date()
          let endTime = new Date()
          endTime.setTime(endTimeTamp * 1000)
          this.timeRemain = this.$utils.timeDif(currentTime, endTime)
        }
      }
    }
  }
</script>

<style>
  .DetailsEntry:before {
    content: none;
  }

  .bg_d3d2d2 {
    background-color: #d3d2d2;
  }

  .collected {
    color: #f83166;
  }
</style>
